<template>
  <el-card class="clubListMain" style="max-width: 75vw">
    <div>
      <el-table class="listTable" :data="clubListData" :border=true style="width: 100%" :max-height="'70vh'">
        <el-table-column prop="clubName" label="社团名称" :width="tableWidth[0]" :align="'center'" />
        <el-table-column prop="level" label="社团级别" :width="tableWidth[1]" :align="'center'" />
        <el-table-column prop="number" label="社团人数" :width="tableWidth[2]" :align="'center'" />
        <el-table-column prop="status" label="社团状态" :width="tableWidth[3]" :align="'center'" />
        <el-table-column prop="options" label="操作" :width="tableWidth[4]" :align="'center'">
          <template #default="scope">
            <el-button id="buttonClubShow" @click="handleShowClub(scope.row)">查看社团详情</el-button>
            <el-button id="" @click="handleShowMembers(scope.row)">查看成员</el-button>
            <el-button type="primary" id="" @click="handleChangeInfo(scope.row)">修改信息</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-card>

  <el-dialog v-model="dialogVisible" title="修改社团信息" width="800">
    <el-form  label-width="auto">
      <el-form-item label="头像">
        <div class="avatarChange">
          <el-avatar id="avatarImg" :size="55" :src="clubFormData.backImage" />
          <el-upload class="avatar-uploader" :beforeUpload="beforeImgUpload" :show-file-list="false"
            :accept="'image/jpeg,image/jpg,image/png,.jpg,.png,.jpeg'">
            <el-button id="uploadButton" type="primary">修改头像</el-button>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="社团名称">
        <el-input v-model="clubFormData.clubName" style="width: 260px"/>
      </el-form-item>
      <el-form-item label="社团级别">
        <el-radio-group v-model="clubFormData.clubLevel">
          <el-radio :value="1">院级</el-radio>
          <el-radio :value="0">校级</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="社团状态">
        <el-radio-group v-model="clubFormData.clubState">
          <el-radio :value="0">正常</el-radio>
          <el-radio :value="1">不可加入</el-radio>
          <el-radio :value="2">停用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="社团负责人">
          <el-input v-model="adminName" style="width: 240px" placeholder="输入姓名关键词" />
          <el-button @click="lookupAdmin">查询负责人</el-button>
          <el-button @click="clearAdmin">清除已选</el-button>
      </el-form-item>
      <el-form-item label="社团简介">
        <el-input v-model="clubFormData.introduction" type="textarea" maxlength="500" show-word-limit placeholder="请输入社团简介"/>
      </el-form-item>
      <el-form-item label="申请原因">
        <el-input v-model="clubFormData.reason" type="textarea" maxlength="200" show-word-limit placeholder="请输入申请原因"/>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit">提交</el-button>
      </div>
    </template>
  </el-dialog>

  <el-drawer v-model="drawer" title="查询结果如下" direction='ltr' >
    <span>
      <el-select @change="newAdmin"
      v-model="adminSelect"
      placeholder="--请选择--"
      size="large"
      style="width: 300px"
    >
      <el-option
       v-for="item in options" 
       :key="item.id"
       :label="item.id+`&nbsp&nbsp`+item.userName"
       :value="item.id"
      />
    </el-select>
    </span>
  </el-drawer>
</template>

<script setup>
import { onMounted, reactive, ref, onUnmounted } from 'vue';
import api from '@/api';
import showMessageTip from '@/utils/showMessage';
import userStore from '@/stores/store';
import router from '@/router';
import debounce from '@/utils/debounce';

const clubListData = ref([]);
const tableWidth=ref([]);
const tableWidthRatio=ref([0.27,0.11,0.09,0.15,0.33]);
const dialogVisible = ref(false);
const clubFormData = reactive({
  clubName: '',
  backImage:'',
  clubLevel: -1,
  clubState: -1,
  introduction: '',
  reason: '',
  managerId: null
});
const temp = reactive({});
const imgData = ref(null);
const clubId = ref();
const drawer=ref(false);
const adminSelect= ref(null);
const options = ref([]);
const adminName = ref('');
var debounceSetColumnSize = null;

onMounted(async  () => {
  const width = document.querySelector('.clubListMain').getBoundingClientRect().width-40;
  tableWidth.value[4]=width;
  for(let i = 0; i<4 ;i++){
    tableWidth.value[i] = tableWidthRatio.value[i]*width;
    tableWidth.value[4] -= tableWidth.value[i];
  }
  await handleUpdateList();
});
onMounted( () => {
  debounceSetColumnSize = debounce(setColumnSize, 300);
  window.addEventListener('resize', debounceSetColumnSize);
})
onUnmounted(() => {
  window.removeEventListener('resize', debounceSetColumnSize);
  debounceSetColumnSize.cancel();
});
const setColumnSize = () => {
  const width = document.querySelector('.clubListMain').getBoundingClientRect().width-40;
  tableWidth.value[4]=width;
  for(let i = 0; i<4 ;i++){
    tableWidth.value[i] = tableWidthRatio.value[i]*width;
    tableWidth.value[4] -= tableWidth.value[i];
  }
}

const handleUpdateList = async() => {
  const resultList =await api.getManagedClub();
  switch(resultList[0])
    {
      case 0:
        const data = resultList[1].data;
        if(data.code == 1){
          const tableData = data.data;
          for(let i=0;i<tableData.length;i++){
            const temp = reactive({});
            if(tableData[i].clubLevel == 0){
              temp.level = "校级";
            }
            else{
              temp.level = "院级";
            }
            if(tableData[i].clubState == 0){
              temp.disabled = false;
              temp.status = "可加入"
            }
            else if(tableData[i].clubState == 1){
              temp.disabled = true;
              temp.status = "不可加入";
            }
            else{
              temp.disabled = true;
              temp.status = "停用";
            }
            Object.assign(temp,{
              clubName:tableData[i].clubName,
              number:tableData[i].number,
              clubId:tableData[i].clubId,
            });
            clubListData.value[i] = temp;
          }
        }
        else{
          showMessageTip("加载失败！",'error');
          return;
        }
        break;
      case 1:
        showMessageTip("服务器响应错误，代码:"+resultList[1].status+"，请再次尝试",'error')
        break;
      case 2:
        showMessageTip("连接服务器失败,请检查网络",'error')
        break;
      case 3:
        showMessageTip("请求发送失败",'error')
        break;
    }
}

const handleChangeInfo = async (rowData) => {
  await getClubInfo(rowData.clubId);
  clubId.value = rowData.clubId;
  dialogVisible.value = true;
}

const getClubInfo = async (clubId) => {
  const reqData = await api.getBasicClubInfo({ clubId:clubId });
  if(reqData[0] == 0){
    const data = reqData[1].data;
    if(data.code == 1){
      clearData(clubFormData);
      clearData(temp);
      Object.assign(clubFormData,{...data.data});
      Object.assign(temp,{...clubFormData});
    }
    else{
      Object.assign(temp,{...clubFormData});
      showMessageTip('数据获取失败','error');
      return;
    }
  }
  else{
    showMessageTip('网络请求失败','error');
    dialogVisible.value = false;
    return;
  }
}

const onSubmit = async () => {
  let flag = false;
  const formData = new FormData();
  if(imgData.value != null){
    formData.append('image',imgData.value);
    flag = true;
  }
  if(clubFormData.clubName == ''){
    showMessageTip('社团名不能为空','warning')
    return;
  }
  else if(clubFormData.clubName != temp.clubName){
    formData.append('value1',clubFormData.clubName);
    flag = true;
  }
  if(clubFormData.introduction != temp.introduction){
    formData.append('value4',clubFormData.introduction);
    flag = true;
  }
  if(clubFormData.clubState != temp.clubState){
    formData.append('value6',clubFormData.clubState);
    flag = true;
  }
  if(clubFormData.clubLevel != temp.clubLevel){
    formData.append('value3',clubFormData.clubLevel);
    flag = true;
  }
  if(adminSelect.value != null && adminSelect.value != clubFormData.managerId){
    formData.append('value2',adminSelect.value);
    flag = true;
  }
  if(flag == false){
    showMessageTip('未修改任何信息！','warning');
    return;
  }
  if(clubFormData.reason != ''){
    formData.append('reason',clubFormData.reason);
  }
  else{
    showMessageTip('申请原因不能为空','warning');
    return;
  }
  formData.append('bigAffairType',1);
  formData.append('affairType',2);
  formData.append('clubId',clubId.value);
  const result = await api.applicationAffairs(formData)
  if(result[0] == 0){
    const data = result[1].data;
    if(data.code == 1){
      clearData(temp);
      clearData(clubFormData);
      imgData.value = null;
      showMessageTip('提交成功','success');
      dialogVisible.value = false;
      return;
    }
    else{
      showMessageTip('提交失败','error');
      return;
    }
  }
  else{
    showMessageTip('网络请求失败！','error');
    return;
  }
}

const clearData = (data) => {
  data.clubName = '';
  data.introduction = '';
  data.clubState = -1;
  data.backImage = '';
  data.clubLevel = -1;
  data.reason = '';
  data.managerId = null;
}

const beforeImgUpload = async (file) => {
    if (!file.type.startsWith('image/')) {
        showMessageTip('不支持的文件格式', 'warning');
        return false;
    }
    else if (!(file.size / 1024 / 1024 < 2)) {
        showMessageTip('文件不能大于2M', 'warning')
        return false;
    }
    else {
        imgData.value = file;
        if (imgData.value != null) {
            clubFormData.backImage = await imgToUrl(imgData.value);
            showMessageTip('图片加载成功！', 'success');
        }
        return false;
    }
}
const imgToUrl = (file) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (event) => {
            resolve(event.target.result); // 返回Base64URL
        };
        reader.onerror = (error) => {
            reject(new Error('文件读取错误' + error));
        };
        reader.readAsDataURL(file);
    });
}
const newAdmin = () => {
  clubListData.admin=adminSelect.value;
  const temp =ref();
  temp.value = options.value.find(item =>item["id"]===adminSelect.value );
  adminName.value=temp.value.userName;
}
const lookupAdmin = async () => {
  const searchResult = await api.getSbIdName({ userName: adminName.value });
  if (searchResult[0] == 0) {
    const data = searchResult[1].data;
    if (data.code == 1) {
      drawer.value = true;
      const researchList = data.data;
      options.value = [];
      options.value = researchList;
      showMessageTip('查询成功', 'success');
      return;
    }
    else{
      showMessageTip('数据获取失败', 'error');
    }
  }
  else {
    showMessageTip('网络请求失败', 'error');
    return;
  }
};
const clearAdmin = () => {
  adminSelect.value = null;
  adminName.value = '';
}
const handleShowClub = (rowData) => {
  userStore().setClubID(rowData.clubId);
  router.push('clubview');
}
const handleShowMembers = (rowData) => {
  userStore().setClubID(rowData.clubId);
  router.push('memberinfo');
}
</script>

<style scoped>
:deep(.listTable .el-table__header-wrapper th){
  background-color: #549DFD;
  color: #fff;
  font-family: 'Microsoft YaHei';
}
.avatarChange{
  display: flex;
  align-items: center;
}
#uploadButton{
  margin-left: 20px;
}
</style>